extends Node2D
@onready var ui: MarginContainer = $CanvasLayer/UI
@onready var start: TextureButton = $CanvasLayer/CenterContainer/Start
@onready var game_over: TextureButton = $CanvasLayer/CenterContainer/GameOver

var enemy = preload("res://scene/enemy.tscn")
var score := 0

func _on_enemy_died(value):
	score += value
	ui.update_score(score)
	#print("count:",get_tree().get_nodes_in_group("enemies").size())
	if get_tree().get_nodes_in_group("enemies").size() ==1:
		game_over.show()
		await get_tree().create_timer(2).timeout
		game_over.hide()
		start.show()
		$Player.queue_free()
		createPlayer()

func _ready():
	start.show()

func spawn_enemies():
	for x in range(9):
		for y in range(3):
			var e = enemy.instantiate()
			var pos = Vector2(x * (16 + 8) + 24, 16 * 4 + y * 16)
			add_child(e)
			e.start(pos)
			e.died.connect(_on_enemy_died)


func _on_player_hurt(num) -> void:
	ui.update_shield(100,num)


func _on_start_pressed() -> void:
	start.hide()
	new_game()
	
func new_game():
	spawn_enemies()
	ui.update_shield(100,100)


func _on_player_died() -> void:
	print("on game over....")
	get_tree().call_group("enemies", "queue_free")
	game_over.show()
	await get_tree().create_timer(2).timeout
	game_over.hide()
	start.show()
	createPlayer()
	

func createPlayer():
	var player = preload("res://scene/player.tscn").instantiate()
	player.name = "Player"
	add_child(player)
	#重新添加信号链接
	player.died.connect(_on_player_died)
	player.hurt.connect(_on_player_hurt)
